package com.asset.salesforce.controller;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.asset.salesforce.converter.JoinRequestConverter;
import com.asset.salesforce.converter.ProfileConverter;
import com.asset.salesforce.domain.ChatterContribution;
import com.asset.salesforce.domain.City;
import com.asset.salesforce.domain.Company;
import com.asset.salesforce.domain.Country;
import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.domain.File;
import com.asset.salesforce.domain.Role;
import com.asset.salesforce.domain.User;
//import com.asset.salesforce.domain.Industry;
import com.asset.salesforce.domain.JobTitle;
import com.asset.salesforce.domain.JoinRequest;
import com.asset.salesforce.domain.Lead;
//import com.asset.salesforce.domain.LeadSource;
//import com.asset.salesforce.domain.LeadStatus;
import com.asset.salesforce.domain.Login;
import com.asset.salesforce.domain.Post;
//import com.asset.salesforce.domain.Rating;
import com.asset.salesforce.enums.INDUSTRY;
import com.asset.salesforce.enums.LEADSOURCE;
import com.asset.salesforce.enums.LEADSTATUS;
import com.asset.salesforce.enums.RATING;
//import com.asset.salesforce.form.ChangePasswordForm;
import com.asset.salesforce.form.EmpRegister;
import com.asset.salesforce.form.JoinRequestForm;
import com.asset.salesforce.form.OwnRegisterForm;
import com.asset.salesforce.form.ProfileForm;
//import com.asset.salesforce.service.CheckingUtilsService;
//import com.asset.salesforce.service.BootstrapDataPopulator;
import com.asset.salesforce.service.CalendarService;
import com.asset.salesforce.service.ChatterContributionService;
import com.asset.salesforce.service.CheckingUtilsService;
import com.asset.salesforce.service.CityService;
import com.asset.salesforce.service.CompanyService;
import com.asset.salesforce.service.CountryService;
import com.asset.salesforce.service.FileService;
import com.asset.salesforce.service.RoleShiroService;
import com.asset.salesforce.service.UserShiroService;
//import com.asset.salesforce.service.IndusteryService;
import com.asset.salesforce.service.JobTitleService;
import com.asset.salesforce.service.JoinRequestService;
import com.asset.salesforce.service.LeadService;
//import com.asset.salesforce.service.LeadSourceService;
//import com.asset.salesforce.service.LeadStatusService;
import com.asset.salesforce.service.PostService;
//import com.asset.salesforce.service.RatingService;
import com.asset.salesforce.service.ViewService;
//import com.asset.salesforce.service.DepartmentService;
import com.asset.salesforce.service.EmployeeService;
//import com.asset.salesforce.service.FileService;
import com.asset.salesforce.service.LoginService;
import com.asset.salesforce.view.PdfView;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

@Controller
public class EmployeeController {

	@Autowired
	FileService fileService;

	@Autowired
	JavaMailSender mailSender;

	@Autowired
	private CityService cityService;

	@Autowired
	private EmployeeService employeeService;

	@Autowired
	private CompanyService companyService;

	@Autowired
	private LeadService leadService;
	@Autowired
	private JoinRequestService joinRequestService;
	@Autowired
	CalendarService calendarService;
	//
	// @Autowired
	// private LeadStatusService leadStatusService;
	//
	// @Autowired
	// private LeadSourceService leadSourceService;
	//
	// @Autowired
	// private RatingService ratingService;
	//
	// @Autowired
	// private IndusteryService industeryService;
	// check for siro inserts

	@Autowired
	private UserShiroService userShiroService;

	@Autowired
	private RoleShiroService roleShiroService;

	// @Autowired
	// private BootstrapDataPopulator bootstrapDataPopulator;

	@Autowired
	private CountryService countryService;

	@Autowired
	private JobTitleService jobTitleService;

	@Autowired
	private LoginService loginService;

	@Autowired
	private FileService filService;

	@Autowired
	private PostService postService;

	@Autowired
	private ChatterContributionService chatterContributionService;

	@Autowired
	private CheckingUtilsService checkingUtilsService;

	@Autowired
	private ViewService viewService;

	@RequestMapping("/logout")
	public String logout() {
		SecurityUtils.getSubject().logout();
		return "redirect:/";
	}

	@RequestMapping(value = "/thanks", method = RequestMethod.GET)
	public String getthank(HttpSession session, Model model) {
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		model.addAttribute("userDetails", userDetails);
		return "thanks";
	}

	@RequestMapping(value = "/empRegThanks", method = RequestMethod.GET)
	public String getEmpRegThanks(HttpSession session, Model model) {
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		model.addAttribute("userDetails", userDetails);
		return "empRegThanks";
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String get(HttpSession session, Model model) {
		// Employee userDetails = (Employee)session.getAttribute("userDetails");
		// bootstrapDataPopulator.afterPropertiesSet();
		// model.addAttribute("userDetails",userDetails);
		return "register";
	}

	@SuppressWarnings("resource")
	@RequestMapping(value = "/ownerRegister", method = RequestMethod.POST)
	public String postRegister(HttpServletRequest request, HttpSession session,
			Model model, @Valid OwnRegisterForm ownRegisterForm,
			BindingResult result) {
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+email);
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+fName);
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+lName);
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+username);
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+phone);
		if (result.hasErrors()) {
			Employee userDetails = (Employee) session
					.getAttribute("userDetails");
			model.addAttribute("userDetails", userDetails);
			List<Country> countries = new ArrayList<Country>();
			countries = countryService.getAll();
			// System.out.println("???????????????????????????????????????????????????????????????????"+countries.size());

			model.addAttribute("countries", countries);

			return "ownerRegister";
		}
		Employee employee = new Employee();
		Company company1 = new Company();
		company1.setCompanyName(ownRegisterForm.getCompany());
		company1.setEmployeesNumber(ownRegisterForm.getEmpNum());
		companyService.addCompany(company1);
//		String imagePath = "noprofile.jpg";
//	      ClassLoader imagecl = EmployeeController.class.getClassLoader();
//	      URL imgURL = imagecl.getResource(imagePath);		
//		java.io.File file = new java.io.File(imgURL.getPath());
//		FileInputStream imageInFile;
//		try {
//			imageInFile = new FileInputStream(file);
//			 byte imageData[] = new byte[(int) file.length()];
//		     imageInFile.read(imageData);
//		     String imageDataString = encodeImage(imageData);
//		     File filetoDatabase = new File();
//		     filetoDatabase.setData(imageDataString.getBytes());
//		     filetoDatabase.setDateCreated(new Date());
//		     filetoDatabase.setName(imagePath);
//		     filetoDatabase.setExtension("image/jpg");
//		     filetoDatabase.setType("image/jpg");
//		     String encode = "data:image/jpeg;base64," + imageDataString;
//		     filetoDatabase.setEncode(encode);
//		     filService.addfile(filetoDatabase);
//		     employee.setPhoto(filetoDatabase);
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		Country empCountry = countryService.getCountryById(ownRegisterForm
				.getCountry());
		employee.setCompany(company1);
		employee.setNickName(ownRegisterForm.getUsername());
		employee.setEmail(ownRegisterForm.getEmail());
		employee.setfName(ownRegisterForm.getfName());
		employee.setIsActive(true);
		employee.setIsOwner(true);
		employee.setlName(ownRegisterForm.getlName());
		employee.setManager(null);
		employee.setRegisterDate(new Date());
		employee.setFirstLogin(true);
		employee.setCountry(empCountry);
		Login login = new Login();
		employeeService.addEmployee(employee);
		Employee employee2 = employeeService.getEmployeeByEmail(ownRegisterForm
				.getEmail());
		System.out.println("<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>"
				+ employee2.getEmail());
		System.out.println("<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>"
				+ employee2.getId());
		// ayyad add chatter
		ChatterContribution chatter = new ChatterContribution();
		chatter.setCountComments(0);
		chatter.setCountPosts(0);
		chatter.setCountRecivedComments(0);
		chatter.setCountRecivedLikes(0);

		chatter.setEmpId(employee.getId());
		chatterContributionService.addChatter(chatter);
		login.setEmail(employee2.getEmail());
		login.setEmpId(employee2.getId());
		login.setPassword(ownRegisterForm.getPassword());
		loginService.addLogin(login);
		System.out
				.println("<<<<<<<<<<<<<<<<<<<<<<<<hiiiiiiiiiiiiiiiiiiiii>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

		// ayyad -- add in users table
		User user1 = new User();
		user1.setEmail(employee2.getEmail());
		user1.setPassword(new Sha256Hash(ownRegisterForm.getPassword()).toHex());
		user1.setUsername(employee2.getEmail());
		user1.setCompanyId(employee);
		//
		List<Role> roles = new ArrayList<Role>();
		roles = roleShiroService.getAllRoles();
		user1.setRoles(roles);
		userShiroService.addUser(user1);
		// Set<Role> roles = new HashSet<Role>();
		// Role ownerRole = roleShiroService.findRole("owner");
		// Role adminRole = roleShiroService.findRole("admin");
		// if(ownerRole != null){
		//
		// roles.add(ownerRole);
		//
		// }
		// if(employee2.getEmail().equals("admin@admin.admin") && adminRole !=
		// null){
		// roles.add(adminRole);
		// }
		// user1.setRoles(roles);
		// userShiroService.addUser(user1);
		// System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< user added");
		// // User user = new User();
		//

		return "thanks";
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String getLogin(HttpSession session) {
		// bootstrapDataPopulator.afterPropertiesSet();
		session.setAttribute("userDetails", null);
		return "login";
	}

	@RequestMapping(value = "/start", method = RequestMethod.GET)
	public String getstart(HttpSession session, Model model) {

		if (null == session.getAttribute("userDetails")) {
			return "redirect:/s/login.html";
		}
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		model.addAttribute("userDetails", userDetails);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "start";
	}

	@RequestMapping(value = "/pendingRequests", method = RequestMethod.GET)
	public String getjoinrequest(HttpSession session, Model model) {
		if (null == session.getAttribute("userDetails")) {
			return "redirect:/s/login.html";
		}
		Employee employee = (Employee) session.getAttribute("userDetails");
		// System.out.println("<<<<<<<<===================="+employee.getId());
		List<JoinRequest> joinRequests = joinRequestService
				.getJoinRequestsByOwnerId(employee.getId());
		// System.out.println(")()()(KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK"+joinRequests.get(0).getEmp().getfName());
		JoinRequestConverter joinRequestConverter = new JoinRequestConverter();
		List<JoinRequestForm> joinRequestForms = joinRequestConverter
				.getPendingRequest(joinRequests);
		model.addAttribute("joinRequestForms", joinRequestForms);
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		model.addAttribute("userDetails", userDetails);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);

		return "pendingRequests";
	}

	@RequestMapping(value = "/acceptRequests", method = RequestMethod.GET)
	public String acceptJoinrequest(HttpSession session, Model model,
			HttpServletRequest request) {
		Integer id = Integer.parseInt(request.getParameter("id").toString());
		Integer empId = Integer.parseInt(request.getParameter("empId")
				.toString());
		Employee employee = employeeService.loadEmployeeById(empId);
		if (employee != null) {
			Login login = new Login();
			login.setEmail(employee.getEmail());
			Random random = new Random();
			// random.setSeed(123456789);
			Integer password = random.nextInt(12345678);
			login.setPassword(password.toString());
			login.setEmpId(empId);
			loginService.addLogin(login);
			JoinRequest joinRequest = joinRequestService.getJoinRequest(id);
			joinRequest.setStatus(1);
			joinRequestService.saveOrupdate(joinRequest);

			// /////////sending emails to with password
			// SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
			String toAddress = employee.getEmail();
			// ayyad -- add in users table

			User user1 = new User();
			user1.setEmail(employee.getEmail());
			user1.setPassword(new Sha256Hash(login.getPassword()).toHex());
			user1.setUsername(employee.getEmail());
			user1.setCompanyId(employee);
			//
			List<Role> roles = new ArrayList<Role>();
			Role role = null;
			// roleShiroService.findRole("leadgenerator");

			String jobTitle = employee.getJobTitle().getName();
			if (jobTitle != null) {
				if (jobTitle.equals("Lead Generator")) {
					role = roleShiroService.findRole("leadgenerator");
				} else if (jobTitle.equals("Sales Manager")) {
					role = roleShiroService.findRole("salesmanager");
				} else if (jobTitle.equals("Sales Man")) {
					role = roleShiroService.findRole("salesman");
				} else if (jobTitle.equals("Bussiness Devlivery")) {
					role = roleShiroService.findRole("bussinessdeveloper");
				}
			}
			roles.add(role);
			user1.setRoles(roles);
			userShiroService.addUser(user1);

			// ayyad add chatter
			ChatterContribution chatter = new ChatterContribution();
			chatter.setCountComments(0);
			chatter.setCountPosts(0);
			chatter.setCountRecivedComments(0);
			chatter.setCountRecivedLikes(0);
			chatter.setEmpId(employee.getId());
			chatterContributionService.addChatter(chatter);

			String txt = "<div style='font-family: verdana,arial,sans-serif; font-size: 12px; color: rgb(85, 85, 85);  border: 1px solid rgb(0, 0, 0); width: 550px; height: 370px; background: none repeat scroll 0% 0% rgb(255, 255, 255); box-shadow: 0px 0px 15px rgb(204, 204, 204);'>"
					+ "<h4 style='margin: 0px 0px 10px 0px; width: 530px; background: none repeat scroll 0% 0% rgb(0, 0, 0); font-size: 17px; font-weight: bold; padding: 10px; color: rgb(242, 242, 242);'>Asset Group CRM</h4>"
					+ "<h5 style='margin: 0 10px; padding: 0px; font-size: 12px;'>Hi "
					+ employee.getfName()
					+ ",</h5>"
					+ "<br/>"
					+ "<p style='margin: 0 10px; text-align: justify; line-height: 20px; padding: 0;'>Thanks for joining Asset Group CRM that's fast, efficient and maybe even fun.</p>"
					+ "<br/>"
					+ "<p style='margin: 0 10px; text-align: justify; line-height: 20px; padding: 0;'>Your request to join "
					+ employee.getfName()
					+ " company is accepted and your account has been created � now it will be easier than ever to share and connect with your co-workers.</p>"
					+ "<br/>"
					+ "<p style='margin: 0 10px; text-align: justify; line-height: 20px; padding: 0;'>You can login now with your email:"
					+ "<br/><span style='margin: 0 10px; font-weight: bold; color: rgb(0, 0, 0);'>"
					+ employee.getEmail()
					+ "</span>"
					+ "<br/>and password:"
					+ "<br/><span style='margin: 0 10px; font-weight: bold; color: rgb(0, 0, 0);'> "
					+ password.toString()
					+ "</span></p>"
					+ "<br/>"
					+ "<p style='margin: 0 10px; text-align: justify; line-height: 20px; padding: 0;'>To complete the sign-up process, please follow this link to set a new password:</p>"
					+ "<br/>"
					+ "<a href='http://192.168.1.10:8080/sales/login.html' style='margin: 0 10px; float: left; clear: both; color: #0067E7;'>http://192.168.1.10:8080/sales/login.html</a>"
					+ "<br/>"
					+ "<span style='margin: 0 10px 7px; float: left; clear: both; padding: 0;'>Thanks,</span>"
					+ "<br/>"
					+ "<span style='margin: 0 10px 15px; float: left; clear: both; padding: 0;'>Asset Group CRM Team.</span>"
					+ "</div>";
			MimeMessage message = mailSender.createMimeMessage();
			try {
				MimeMessageHelper helper = new MimeMessageHelper(message, true);

				helper.setTo(toAddress);
				helper.setSubject("Asset Group CRM Registeration confirmation ");

				helper.setText(txt, true);
			} catch (Exception e) {
				e.printStackTrace();
			}

			mailSender.send(message);

			Employee userDetails = (Employee) session
					.getAttribute("userDetails");
			model.addAttribute("userDetails", userDetails);
			return "redirect:/s/pendingRequests.html";
		} else {
			return "login";
		}

	}

	@RequestMapping(value = "/refuseRequests", method = RequestMethod.GET)
	public String refuseJoinrequest(HttpSession session, Model model,
			HttpServletRequest request) {
		Integer id = Integer.parseInt(request.getParameter("id").toString());
		JoinRequest joinRequest = joinRequestService.getJoinRequest(id);
		joinRequest.setStatus(2);
		joinRequestService.saveOrupdate(joinRequest);
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		model.addAttribute("userDetails", userDetails);
		return "redirect:/s/pendingRequests.html";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String postLogin(
			HttpSession session,
			@RequestParam(value = "username", required = false) String username,
			@RequestParam(value = "password", required = false) String password) {
		Login login = loginService.getLogin(password, username);
		System.out.println("login>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
				+ login.getEmail());
		String forword = "";
		if (login.getEmail() == null && login.getPassword() == null) {
			forword = "login";
		} else {
			Employee employee = employeeService.getEmployeeByEmailAndPassword(
					login.getEmail(), login.getPassword());
			boolean isActive = employee.getIsActive();
			boolean isOwner = employee.getIsOwner();
			boolean isFirstLogin = employee.getFirstLogin();
			if (!isOwner && !isActive) {
				// create shiro accesss token
				UsernamePasswordToken token = new UsernamePasswordToken(
						username, password, false);
				try {
					SecurityUtils.getSubject().login(token);
				} catch (AuthenticationException e) {
					System.out
							.println(">>>>>>>>>>>><<<<<<<<<<<<<<<<shirooooooo error>>>>>>>>>>>>>>>>>>>>");
					e.printStackTrace();

				}
				forword = "redirect:/s/changePassword";
			} else if (isActive && isFirstLogin) {
				employee.setFirstLogin(false);
				employeeService.saveOrUpdateEmployee(employee);
				// create shiro accesss token
				UsernamePasswordToken token = new UsernamePasswordToken(
						username, password, false);
				try {
					SecurityUtils.getSubject().login(token);
				} catch (AuthenticationException e) {
					System.out
							.println(">>>>>>>>>>>><<<<<<<<<<<<<<<<shirooooooo error>>>>>>>>>>>>>>>>>>>>");
					e.printStackTrace();

				}
				forword = "redirect:/s/start";
			} else if (isActive && !isFirstLogin) {
				// create shiro accesss token
				UsernamePasswordToken token = new UsernamePasswordToken(
						username, password, false);
				try {
					SecurityUtils.getSubject().login(token);
				} catch (AuthenticationException e) {
					System.out
							.println(">>>>>>>>>>>><<<<<<<<<<<<<<<<shirooooooo error>>>>>>>>>>>>>>>>>>>>");
					e.printStackTrace();

				}
				forword = "redirect:/s/home.html";
			} else {
				forword = "register";
			}

			// Subject currentUser = SecurityUtils.getSubject();
			//
			// Session session2 = currentUser.getSession();
			// session2.setAttribute("user",login);
			// session2.setAttribute("userDetails",employee);
			session.setAttribute("user", login);
			session.setAttribute("userDetails", employee);
			// forword = "start";
		}
		return forword;
	}

	@RequestMapping(value = "/ownerRegister", method = RequestMethod.GET)
	public String getownerRegister(HttpSession session, Model model) {
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		model.addAttribute("userDetails", userDetails);
		List<Country> countries = new ArrayList<Country>();
		countries = countryService.getAll();
		System.out
				.println("???????????????????????????????????????????????????????????????????"
						+ countries.size());
		OwnRegisterForm ownRegisterForm = new OwnRegisterForm();
		model.addAttribute("ownRegisterForm", ownRegisterForm);
		model.addAttribute("countries", countries);
		return "ownerRegister";
	}

	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public String gethome(HttpSession session, Model model) {
		if (null == session.getAttribute("userDetails")) {
			return "redirect:/s/login.html";
		}
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		Employee employeeChatter = (Employee) session
				.getAttribute("userDetails");
		List<Post> posts = new ArrayList<Post>();
		posts = postService.getAllPostsByEmpId(employeeChatter);
		model.addAttribute("posts", posts);
		model.addAttribute("userDetails", userDetails);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "home";
	}
	

	@RequestMapping(value = "/profile", method = RequestMethod.GET)
	public String getprofile(HttpSession session, Model model) {
		if (null == session.getAttribute("userDetails")) {
			return "redirect:/s/login.html";
		}
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		Country country = userDetails.getCountry();
		Integer countryId = null;
		Country userCountry = null;
		if (country != null) {
			countryId = country.getId();
			userCountry = countryService.getCountryById(countryId);
		}
		
		Employee employeeChatter = (Employee) session
				.getAttribute("userDetails");
		List<Post> posts = new ArrayList<Post>();
		posts = postService.getAllPostsByEmpId(employeeChatter);
		ChatterContribution chatter = chatterContributionService
				.getChatterByEmployee(userDetails.getId());
		model.addAttribute("chatter", chatter);
		model.addAttribute("posts", posts);
		model.addAttribute("userCountry", userCountry);
		model.addAttribute("userDetails", userDetails);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "profile";
	}

	@RequestMapping(value = "/edit-profile", method = RequestMethod.GET)
	public String editprofile(HttpSession session, Model model) {
		if (null == session.getAttribute("userDetails")) {
			return "redirect:/s/login.html";
		}
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		List<JobTitle> jobTitles = jobTitleService.getAllJobtitle();
		ProfileConverter profileConverter = new ProfileConverter();
		ProfileForm profileForm = profileConverter.addToProfileForm(userDetails);
		
		model.addAttribute("profileForm",profileForm);
		model.addAttribute("jobTitles", jobTitles);
		model.addAttribute("userDetails", userDetails);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "edit-profile";
	}

	@RequestMapping(value = "/edit-profile", method = RequestMethod.POST)
	public String editProfile(
			HttpSession session,
			Model model,
			HttpServletRequest request,
			HttpServletResponse response,
//			@RequestParam(value = "fName", required = false) String fName,
//			@RequestParam(value = "lName", required = false) String lName,
//			@RequestParam(value = "jobTitle", required = false) Integer jobTitle,
//			@RequestParam(value = "nickName", required = false) String nickName,
//			@RequestParam(value = "empInfo", required = false) String empInfo,
//			@RequestParam(value = "fileInput", required = false) MultipartFile fileInput
			@Valid ProfileForm profileForm,BindingResult result) {
		if (null == session.getAttribute("userDetails")) {
			return "redirect:/s/login.html";
		}
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<"+password);
		// System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<"+repassword);
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		
		if (result.hasErrors()) {
			List<JobTitle> jobTitles = jobTitleService.getAllJobtitle();
			model.addAttribute("profileForm",profileForm);
			File userPhoto = userDetails.getPhoto();
			if (userPhoto != null) {
				Integer photoId = userPhoto.getId();
				File file = fileService.getFileById(photoId);
				try {
					String encodeImage = Base64.encode(file.getData());
					model.addAttribute("encodeImage", encodeImage);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			model.addAttribute("userPhoto", userPhoto);
			model.addAttribute("jobTitles", jobTitles);
			model.addAttribute("userDetails", userDetails);
			joinRequestService.getJoinRquestNo(session, model);
			calendarService.getAppointmentEventsNo(session, model);
			calendarService.getCallEventssNo(session, model);

			return "edit-profile";
		}
		
		if (profileForm.getJobTitle() != null) {
			JobTitle jobTitleObj = jobTitleService.getJobtitleById(profileForm.getJobTitle());
			userDetails.setJobTitle(jobTitleObj);
		}
		userDetails.setfName(profileForm.getfName());
		userDetails.setlName(profileForm.getlName());
		userDetails.setNickName(profileForm.getNickName());
		userDetails.setEmpInfo(profileForm.getEmpInfo());
		Integer photoId = null;
		File userPhoto = userDetails.getPhoto();
		if (userPhoto != null) {
			photoId = userPhoto.getId();
		}
		System.out.println(profileForm.getfName()
				+ " *************/////////////////****************** "
				+ profileForm.getFileInput());
		if ( profileForm.getFileInput().getOriginalFilename() != null
				&& ! profileForm.getFileInput().getOriginalFilename().equalsIgnoreCase("")
				&&  profileForm.getFileInput().getContentType().startsWith("image")) {
			File file;
			if (photoId != null) {
				file = fileService.getFileById(photoId);
			} else {
				file = new File();
			}
			try {
				file.setData( profileForm.getFileInput().getBytes());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			file.setDateCreated(new Date());
			file.setName(profileForm.getFileInput().getOriginalFilename());
			file.setExtension(profileForm.getFileInput().getContentType());
			file.setType(profileForm.getFileInput().getContentType());
			String encodeImage = Base64.encode(file.getData());
			String encode = "data:image/jpeg;base64," + encodeImage;
			System.out.println(encode
					+ "jjjjjjjjjjjjjjjjjjjjbbbbbbbbbbbbbbbbbb "
					+ encodeImage.length());
			System.out.println(encode
					+ "jjjjjjjjjjjjjjjjjjjjbbbbbbbbbbbbbbbbbb "
					+ encode.length());
			file.setEncode(encode);
			fileService.saveOrUpdateFile(file);
			userDetails.setPhoto(file);
		}
		employeeService.saveOrUpdateEmployee(userDetails);
		model.addAttribute("userDetails", userDetails);
		return "redirect:/s/profile.html";
	}

	 @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
     public String postchangePassword(
                     HttpSession session,
                     Model model,
                     HttpServletRequest request,
                     HttpServletResponse response,
                     @RequestParam(value = "CHpassword", required = false) String password,
                     @RequestParam(value = "CHrePassword", required = false) String repassword,
                     @RequestParam(value="oldPassword",required = false)String oldPassword) {
             if (null == session.getAttribute("userDetails")) {
                     return "redirect:/s/login.html";
             }
             // System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<"+password);
             // System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<"+repassword);
             Employee userDetails = (Employee) session.getAttribute("userDetails");
             Login login = (Login) session.getAttribute("user");
             login.setPassword(repassword);

             userDetails.setIsActive(true);
             loginService.saveOrUpdate(login);
             employeeService.saveOrUpdateEmployee(userDetails);

             User user1 = userShiroService.findUser(userDetails.getEmail());
             user1.setEmail(userDetails.getEmail());
             user1.setUsername(userDetails.getEmail());
             user1.setPassword(new Sha256Hash(repassword).toHex());
             userShiroService.editUser(user1);

             model.addAttribute("userDetails", userDetails);

             return "redirect:/s/login.html";
     }


    @RequestMapping(value = "/changePassword", method = RequestMethod.GET)
    public String getchangePassword(HttpSession session, Model model) {
            if (null == session.getAttribute("userDetails")) {
                    return "redirect:/s/login.html";
            }
            Employee userDetails = (Employee) session.getAttribute("userDetails");
            Login login = (Login) session.getAttribute("user");
           // User user = userShiroService.getUserById(userDetails.getId());
            model.addAttribute("empPassword",login.getPassword());
            model.addAttribute("userDetails", userDetails);
            joinRequestService.getJoinRquestNo(session, model);
            calendarService.getAppointmentEventsNo(session, model);
            calendarService.getCallEventssNo(session, model);
            return "changePassword";
    }


	@RequestMapping(value = "/empRegister", method = RequestMethod.GET)
	public String getempRegister(HttpSession session, Model model) {
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		List<Country> countries = countryService.getAll();
		List<JobTitle> jobTitles = jobTitleService.getAllJobtitle();
		EmpRegister empRegister = new EmpRegister();
		model.addAttribute("empRegister", empRegister);
		model.addAttribute("countries", countries);
		model.addAttribute("jobTitles", jobTitles);
		model.addAttribute("userDetails", userDetails);
		return "empRegister";
	}

	@RequestMapping(value = "/empRegister", method = RequestMethod.POST)
	public String postempRegister(HttpSession session, Model model,
			@Valid EmpRegister empRegister, BindingResult result) {
		Employee userDetails = (Employee) session
				.getAttribute("userDetails");
		
		List<Employee> employees = employeeService.getAll();
		
		for (Employee employee : employees) {
			if(employee.getEmail().equals(empRegister.getEmail())){
				JoinRequest request = joinRequestService.getJoinRequestByEmpId(employee.getId());
				if(request!=null&&request.getStatus()==2){
					result.rejectValue("email", "email","This email is already rejected ");
				}
				else{
					result.rejectValue("email", "email","Please,Enter a different email");
				}
				
			}
		}
		if (result.hasErrors()) {
			List<Country> countries = countryService.getAll();
			List<JobTitle> jobTitles = jobTitleService.getAllJobtitle();
			model.addAttribute("countries", countries);
			model.addAttribute("jobTitles", jobTitles);
			model.addAttribute("agree", empRegister.getChbox());
			// model.addAttribute("countryForm", empRegister.getCountry());
			// model.addAttribute("jobTitleForm", empRegister.getJobTitle());

			model.addAttribute("userDetails", userDetails);
			return "empRegister";
		}
		JobTitle jobTitleObj = jobTitleService.getJobtitleById(empRegister
				.getJobTitle());
		Employee empOwner = employeeService.getOwnerByCompanyName(empRegister
				.getCompany());
		Employee employee = new Employee();
		Country empCountry = countryService.getCountryById(empRegister
				.getCountry());
//		String imagePath = "noprofile.jpg";
//	      ClassLoader imagecl = EmployeeController.class.getClassLoader();
//	      URL imgURL = imagecl.getResource(imagePath);		
//		java.io.File file = new java.io.File(imgURL.getPath());
//		FileInputStream imageInFile;
//		try {
//			imageInFile = new FileInputStream(file);
//			 byte imageData[] = new byte[(int) file.length()];
//		     imageInFile.read(imageData);
//		     String imageDataString = encodeImage(imageData);
//		     File filetoDatabase = new File();
//		     filetoDatabase.setData(imageDataString.getBytes());
//		     filetoDatabase.setDateCreated(new Date());
//		     filetoDatabase.setName(imagePath);
//		     filetoDatabase.setExtension("image/jpg");
//		     filetoDatabase.setType("image/jpg");
//		     String encode = "data:image/jpeg;base64," + imageDataString;
//		     filetoDatabase.setEncode(encode);
//		     filService.addfile(filetoDatabase);
//		     employee.setPhoto(filetoDatabase);
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		employee.setEmail(empRegister.getEmail());
		employee.setfName(empRegister.getfName());
		employee.setlName(empRegister.getlName());
		employee.setJobTitle(jobTitleObj);
		employee.setIsActive(false);
		employee.setNickName(empRegister.getUsername());
		employee.setIsOwner(false);
		employee.setFirstLogin(true);
		employee.setRegisterDate(new Date());
		employee.setCompany(empOwner.getCompany());
		employee.setCountry(empCountry);
		employeeService.addEmployee(employee);
		Employee emp = employeeService.getEmployeeByEmail(empRegister
				.getEmail());
		System.out.println("<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>"
				+ empOwner.getId());

		JoinRequest joinRequest = new JoinRequest();
		joinRequest.setOwner(empOwner);
		joinRequest.setEmp(emp);
		joinRequest.setStatus(0);
		joinRequest.setStartDate(new Date());
		joinRequestService.addJoinRequest(joinRequest);
		return "empRegThanks";
	}

	@RequestMapping(value = "/leads", method = RequestMethod.GET)
	public String getleads(HttpSession session, Model model,
			HttpServletResponse response,
			@RequestParam(value = "index", required = false) Integer index,
			@RequestParam(value = "pages", required = false) Integer pages,
			@RequestParam(value = "count", required = false) Integer count,
			@RequestParam(value = "rowNumber", required = false) Integer rowNumber) {
		if (null == session.getAttribute("userDetails")) {
			return "redirect:/s/login.html";
		}
		if (count == null) {
			count = 5;
		}
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		model.addAttribute("userDetails", userDetails);
		List<Lead> leads = new ArrayList<Lead>();
		if (index != null) {
			leads = leadService.getAllLead(index, userDetails.getCompany()
					.getId(), count);
			model.addAttribute("index", index);
			model.addAttribute("pages", pages);
			model.addAttribute("count", count);
		} else {
			Integer size = leadService.getAllLeadSize(userDetails.getCompany()
					.getId());
			if (size == null) {
				leads = leadService.getAllLead(0, userDetails.getCompany()
						.getId(), count);
				model.addAttribute("index", 0);
				model.addAttribute("pages", 0);
				model.addAttribute("count", 5);
			} else {
				Integer numOfPages = size / count;
				System.out
						.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
								+ numOfPages);
				if (size % count > 0) {
					numOfPages++;
				}
				leads = leadService.getAllLead(0, userDetails.getCompany()
						.getId(), count);
				model.addAttribute("index", 0);
				model.addAttribute("pages", numOfPages);
				model.addAttribute("count", count);
			}
		}
		for (Lead lead : leads) {
			lead.setIsFollowed(checkingUtilsService
					.checkIfCurrentFollowThatLead(userDetails, lead));
		}
		// System.out.println("000000000000000000000000000000000000000>>>"+leads.size());
		List<Integer> numbers = new ArrayList<Integer>();
		numbers.add(5);
		numbers.add(10);
		numbers.add(15);
		model.addAttribute("numbers",numbers);
		model.addAttribute("leads", leads);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "leads";
	}

	@RequestMapping(value = "/people", method = RequestMethod.GET)
	public String getPeople(HttpSession session, Model model) {
		if (null == session.getAttribute("userDetails")) {
			return "redirect:/s/login.html";
		}
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		String companyName = userDetails.getCompany().getCompanyName();
		model.addAttribute("userDetails", userDetails);
		List<Employee> companyEmployees = companyService
				.getActivatedEmployeesByCompanyName(companyName);
		if (companyEmployees != null) {
			for (Employee employee : companyEmployees) {
				employee.setIsFollowed(checkingUtilsService
						.checkIfCurrentFollowThatPeople(userDetails, employee));
				// if(!employee.getIsOwner()){
				// if(!employee.getIsActive()){
				// companyEmployees.remove(employee);
				// }
				// }
			}
			model.addAttribute("companyEmployees", companyEmployees);
		}
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "people";
	}

	@RequestMapping(value = "/leadFormCityCountry", method = RequestMethod.POST)
	public @ResponseBody
	String getLeadCities(Model model, HttpSession session,
			HttpServletRequest request) {
		Integer selectedCountry = Integer.parseInt(request.getParameter(
				"selectedCountry").toString());
		List<City> cities = new ArrayList<City>();
		cities = cityService.getAllCityByCountryId(selectedCountry);
		// Integer [] cityId = new Integer[cities.size()];
		// String [] cityName = new String[cities.size()];
		// Integer i = 0;
		String cityIds = "";
		String cityNames = "";
		for (City city : cities) {
			if (cities.size() - 1 == cities.indexOf(city)) {

				cityIds += (city.getId()).toString();
				cityNames += city.getName();
			} else {
				cityIds += (city.getId()).toString();
				cityIds += "?";
				cityNames += city.getName();
				cityNames += "?";
			}
			// cityId[i] = city.getId();
			// cityName[i] = city.getName();
			// i = i+1;
		}
		String citiesList = cityIds + "***" + cityNames;
		return citiesList;

	}

	@RequestMapping(value = "/saveNew", method = RequestMethod.POST)
	public String postsaveNewLead(
			HttpSession session,
			@RequestParam(value = "fname", required = false) String fname,
			@RequestParam(value = "company", required = false) String company,
			@RequestParam(value = "status", required = false) Integer status,
			@RequestParam(value = "lname", required = false) String lname,
			@RequestParam(value = "title", required = false) String title,
			@RequestParam(value = "phone", required = false) String phone,
			@RequestParam(value = "email", required = false) String email,
			@RequestParam(value = "rating", required = false) Integer rating,
			@RequestParam(value = "city", required = false) String city,
			@RequestParam(value = "state", required = false) String state,
			@RequestParam(value = "zipcode", required = false) String zipcode,
			@RequestParam(value = "country", required = false) String country,
			@RequestParam(value = "website", required = false) String website,
			@RequestParam(value = "empnum", required = false) Integer empnum,
			@RequestParam(value = "annual", required = false) Integer annual,
			@RequestParam(value = "description", required = false) String description,
			@RequestParam(value = "leadsource", required = false) Integer leadsource,
			@RequestParam(value = "industry", required = false) Integer industry) {
		// System.out.println(">>>>>>>>>>>>>++++++++++++++++++++++++++"+rating.toString());
		Lead lead = new Lead();
		Employee leadOwner = (Employee) session.getAttribute("userDetails");
		// LeadStatus leadStatus = leadStatusService.getLeadStatusById(status);
		LEADSTATUS[] leadStatus = LEADSTATUS.values();
		if (rating != null) {
			System.out
					.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<inside if >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
			// Rating rating2 = ratingService.getRatingById(rating);
			RATING[] rating2 = RATING.values();
			lead.setRating(rating2[rating].getName());
		}
		if (industry != null) {
			// INDUSTRY industry2 = industeryService.getIndusteryById(industry);
			INDUSTRY[] industry2 = INDUSTRY.values();
			lead.setIndustry(industry2[industry].getName());
		}
		if (leadsource != null) {
			// LeadSource leadSource2 =
			// leadSourceService.getLeadSourceById(leadsource);
			LEADSOURCE[] leadSource2 = LEADSOURCE.values();
			lead.setLeadSource(leadSource2[leadsource].getName());
		}

		lead.setfName(fname);
		lead.setCompanyName(company);
		lead.setLeadStatus(leadStatus[status].getName());
		lead.setlName(lname);
		lead.setLeadOwner(leadOwner);
		lead.setAnnualRevenue(annual);
		lead.setNumOfEmp(empnum);
		lead.setDescription(description);
		lead.setWebSite(website);
		lead.setPhone(phone);
		lead.setTitle(title);
		lead.setEmail(email);
		leadService.addLead(lead);
		return "redirect:/s/newLead.html";
	}

	@RequestMapping(value = "/viewPeople", method = RequestMethod.GET)
	public String getViewPeople(Model model, HttpSession session,
			HttpServletRequest request) {
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "";
	}
	@RequestMapping(value="/viewImage",method=RequestMethod.GET)
	public String getImage(Model model, HttpSession session,HttpServletRequest request){
		
       
		return "profile";	
	}
	public static String encodeImage(byte[] imageByteArray) {
        return Base64.encode(imageByteArray);
    }
}
